import {
  getToken
} from '../../../utils/getToken'

Page({
  data: {
    list: [],
    isDialogShow: false,
    houseId: ''
  },
  onShow() {
    this.getList()
  },
  getList() {
    wx.request({
      url: 'https://live-api.itheima.net/room',
      header: {
        Authorization: 'Bearer ' + getToken()
      },
      method: "GET",
      success: (res) => {
        console.log(res)
        if (res.data.code !== 10000) {
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
        this.setData({
          list: res.data.data
        })
        console.log(this.data.list);
      }
    })
  },
  handleSwipeClose(e) {
    // 观察事件对象e的属性思考你可以用他来做什么？
    console.log('swiper cell 关闭 事件对象', e);
    console.log('左滑删除被点击了')
    //打开弹窗
    this.setData({
      isDialogShow: true,
      houseId: e.mark.houseId
    })
    // 隐藏删除按钮
    e.detail.instance.close()
    // TODO
    // 弹出对话框
    // 隐藏删除按钮
  },

  handleDialogClose(e) {
    // 观察事件对象参数
    console.log('对话框关闭事件对象', e);
    if (e.detail === 'confirm') {
      console.log('关闭');
      // 发请求关闭
      wx.request({
        url: `https://live-api.itheima.net/room/${this.data.houseId}`,
        method: 'DELETE',
        header: {
          Authorization: 'Bearer ' + getToken()
        },
        success: (res) => {
          console.log(res);
          if (res.data.code !== 10000) {
            return wx.showToast({
              title: res.data.message,
              icon: 'none'
            })
          }
          const newList = this.data.list.filter(item =>
            item.id !== this.data.houseId
          )
          console.log('旧', this.data.list);
          this.setData({
            list: newList,
            houseId: '',
          })
        }
      })
    }
    if (e.detail === 'cancel') {
      console.log('点击了取消');
    }
    // TODO
    // 判断用户点击的是取消还是确定
  },

  handleHouseItemClick(e) {
    wx.navigateTo({
      url: `/house_pkg/pages/detail/index?id=${e.mark.id}`,
    });
  },

  addHouse() {
    wx.navigateTo({
      url: '/house_pkg/pages/locate/index',
    });
  },
});